package com.atguigu.gmall.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.Duration;

/**
 * @ClassName GlobalUserAuthGatewayFilter
 * @Description TODO
 * @Author king
 * @Date 2022/11/14 14:05
 * @Version 1.0
 *  内存版的消息队列: 回调,hook机制.
 * //发给网关所有请求
 */
//@Component
@Slf4j
public class ReactorTest implements GlobalFilter//全局过滤器
{
//    //什么是响应式编程
//    public static void main(String[] args) throws IOException {
//        ServerSocket serverSocket = new ServerSocket(8080);
//        System.out.println("服务器启动了...");
//
//        while (true){
//            Socket accept = serverSocket.accept();
//            System.out.println("数据放在缓冲区");
//        }
//
////        int age = 10+1;
////        System.out.println("开始....");
////        Mono<Integer> mono = Mono.just(1);
////        mono.subscribe(item->{
////            System.out.println("张三:" + item);
////        });
////
////        mono.subscribe(item->{
////            System.out.println("李四:" + item);
////        });
////
////        mono.subscribe(item->{
////            System.out.println("王五:" + item);
////        });
////        System.out.println("结束....");
////        Flux<Long> interval = Flux.interval(Duration.ofSeconds(1));
////
////        interval.subscribe(item->{
////            System.out.println(Thread.currentThread().getName() + "张三" + item);
////        });
////
////        interval.subscribe(item->{
////            System.out.println(Thread.currentThread().getName() + "李四" + item);
////        });
//
//        GlobalUserAuthGatewayFilter filter = new GlobalUserAuthGatewayFilter();
//        System.out.println("main方法开始");
//        Mono<Long> haha = filter.haha();
//
//        haha.subscribe(item->{
//            System.out.println("你的结果:" + item);
//        });
//
//        System.out.println("main结束");
//        System.out.println("结果:" + haha.block());
//
//
//    }

//    private Mono<Long> haha() {
//        System.out.println(Thread.currentThread() + "哈哈");
//        return Mono.delay(Duration.ofSeconds(3));
//    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange,
                             GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        log.info("请求开始:..." + request.getURI());

       Mono<Void> filter = chain.filter(exchange).doFinally((item) -> {
           log.info("请求结束:..." + request.getURI());
       });

        return filter;
    }
}
